package com.bmf.mybatisPlus.config;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bmf.core.result.ListUtils;
import com.bmf.core.result.PageResponse;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 *  分页查询返回对象
 * @date 2020-04-14 16:49
 * @author 
 */
@Data
public class MyBatisPlusPageResponse<T> extends PageResponse<T> {



    public MyBatisPlusPageResponse() {
        this.setRecords(new ArrayList<>());
        this.setPageNo(0);
        this.setPageSize(0);
        this.setTotalCount(0);

    }
    public MyBatisPlusPageResponse(IPage<T> page) {

        this.setRecords(page.getRecords());
        this.setPageNo((int)page.getCurrent());
        this.setPageSize((int)page.getSize());
        this.setTotalCount((int)page.getTotal());
    }

    public <E> MyBatisPlusPageResponse(IPage<E> page, Function<E, T> mapper) {

        this.setPageNo((int)page.getCurrent());
        this.setPageSize((int)page.getSize());
        this.setTotalCount((int)page.getTotal());

        if (CollUtil.isEmpty(page.getRecords())) {
            this.setRecords(Collections.emptyList());
        } else {

            this.setRecords(page.getRecords().stream().map(mapper).collect(Collectors.toList()));
        }

    }
    public <E> MyBatisPlusPageResponse(IPage<E> page, Supplier<T> target) {

        this.setPageNo((int)page.getCurrent());
        this.setPageSize((int)page.getSize());
        this.setTotalCount((int)page.getTotal());

        if (CollUtil.isEmpty(page.getRecords())) {
            this.setRecords(Collections.emptyList());
        } else {
            this.setRecords(ListUtils.copyListByStream(page.getRecords(), target));
        }

    }

    public <E> MyBatisPlusPageResponse(IPage<E> page, List<T> records) {
        this.setRecords(records);
        this.setPageNo((int)page.getCurrent());
        this.setPageSize((int)page.getSize());
        this.setTotalCount((int)page.getTotal());
    }
}
